package com.takanafu.haru.code{
	import com.takanafu.haru.core.GlobalManager;
	
	import flash.utils.Dictionary;
	
	import mx.collections.ArrayCollection;
	
	public class CodeUserFunction extends CodeFunction{
		protected var symbol:CodeSymbol = null;
		private var params:ArrayCollection;
		private var body:CodeBase;
		
		public function CodeUserFunction(sym:CodeSymbol,list:ArrayCollection,code:CodeBase){
			this.symbol = sym;
			this.params = list;
			this.body = code;
			if(params != null){
				this.arg_count = params.length;
			}
		}
		public function getName():CodeSymbol{
			return this.symbol;
		}
		override public function toString():String{
			return "<fun>";
		}
		override public function run():CodeBase{
			if(this.symbol != null){
				GlobalManager.setSymbol(this.symbol,this);
			}
			return this;
		}
		override public function exec(params:ArrayCollection):CodeBase{
			var c:CodeBase = null;
			
			setArgs(params);
			
			if(this.body != null){
				c = body.run();
			}
			removeArgs();
			return c;
		}
		
		private function setArgs(args:ArrayCollection):void{
			if(params == null && args == null){
				GlobalManager.pushLocals(new Dictionary());
				return;
			}
			var table:Dictionary = new Dictionary();
			GlobalManager.pushLocals(table);
			var count:int = args.length;
			
			for(var i:int = 0;i < count;i++){
				var sym:CodeSymbol = params.getItemAt(i) as CodeSymbol;
				var c:CodeBase = args.getItemAt(i) as CodeBase;
				
				table[sym] = c;
			}
		}
		private function removeArgs():void{
			GlobalManager.popLocals();
		}
	}
}